/*
 * CAppStateCreateGame.cpp
 *
 *  Created on: 24/12/2012
 *
 */

#include "CAppStatePlayGame.h"
#include "CAppStateManager.h"
#include "CSurface.h"
#include <iostream>
#include <string>
#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include "SurfaceWrapper.h"
#include <string.h>
#include "util.h"
using namespace std;

CAppStatePlayGame CAppStatePlayGame::instance;
extern GAME_STATE gameState;
extern bool connected;

CAppStatePlayGame::CAppStatePlayGame() {
	conf = NICK;
	surface = NULL;
	font = NULL;
	bar = NULL;
	nickWrapper = "";
	ipWrapper = "";
	oldNick = "";
	userIp = NULL;
	color = {0,37,83};
	serverFullSurface = NULL;
	errorSurface = NULL;
	error = false;
	userNick = NULL;
	serverFull = false;
	remoteip = NULL;
	tcpClient = NULL;

}

void CAppStatePlayGame::onKeyDown(SDLKey sym, SDLMod mod, Uint16 unicode) {
	if (conf == NICK) {
		if (sym == SDLK_BACKSPACE) {
			if (!nickWrapper.empty())
				nickWrapper.erase(nickWrapper.length() - 1);
		} else {
			if (nickWrapper.length() < MAX_NICK_LENGHT) {
				if (unicode == ' ' || unicode >= 'a' && unicode <= 'z'
						|| unicode >= 'A' && unicode <= 'Z'
						|| unicode >= '0' && unicode <= '9')
					nickWrapper += (char) unicode;
			}
		}
	} else if (conf == IP) {
		if (sym == SDLK_BACKSPACE) {
			if (!ipWrapper.empty())
				ipWrapper.erase(ipWrapper.length() - 1);
		} else {
			if (ipWrapper.length() < MAX_IP_LENGHT) {
				if (unicode == '.' || unicode >= '0' && unicode <= '9') {
					ipWrapper += (char) unicode;
				}
			}
		}

	}

}

void CAppStatePlayGame::onActivate() {
	gameState = CLIENTE;
	if ((surface = CSurface::onLoad(".//data/imgs/jogar-game.png")) == NULL) {
		return;
	}

	if ((bar = CSurface::onLoad(".//data/imgs/barra_text.png")) == NULL) {
		return;
	}
	font = TTF_OpenFont(".//data/fonts/tahoma.TTF", 18);

	tcpClient = new CClientSocket();
	errorSurface = TTF_RenderText_Blended(font,
			"Nao foi possivel conectar ao servidor! tente novamente. ", color);
	serverFullSurface = TTF_RenderText_Blended(font,
			"Partida iniciada! tente depois!", color);
	SDL_EnableUNICODE(SDL_ENABLE);

}

/**
 * Captura o nick do usuario e o IP do servidor
 */
void CAppStatePlayGame::onLButtonDown(int mX, int mY) {

	if (mX >= 355 && mX <= 745 && mY >= 330 && mY <= 375) {
		conf = NICK;
	} else if (mX >= 355 && mX <= 745 && mY >= 410 && mY <= 455) {
		error = false;
		serverFull = false;
		conf = IP;
	} else if (mX >= 360 && mX <= 530 && mY >= 490 && mY <= 530) {
		//remoteip = new CIpAddress("127.0.0.1", 7777);
		//prepara o socket pra realizar o handshake
		remoteip = new CIpAddress(ipWrapper.c_str(), 7777);
		if (tcpClient->Connect(*remoteip)) {
			if (tcpClient->Ok()) {
				connected = true;
			}
		} else {
			remoteip = NULL;
			error = true;
		}

	} else if (mX >= 570 && mX <= 740 && mY >= 490 && mY <= 530) {
		//entrou no cancelar
		CAppStateManager::setActiveAppState(APPSTATE_MENU, NULL);

	}
}

void CAppStatePlayGame::onDeactivate() {
	SDL_FreeSurface(surface);
	surface = NULL;
	SDL_FreeSurface(bar);
	bar = NULL;
	SDL_FreeSurface(userIp);
	userIp = NULL;
	SDL_FreeSurface(userNick);
	userNick = NULL;
	SDL_FreeSurface(errorSurface);
	errorSurface = NULL;
	SDL_EnableUNICODE(SDL_DISABLE);
}

void CAppStatePlayGame::onLoop() {
	if (connected && tcpClient->Ready()) {
		if (tcpClient->Receive(msg)) {
			GAME_MSG tMsg;
			msg.UnLoadBytes(&tMsg);
			switch (tMsg.action) {
			case SERVER_ACCEPT:
				CAppStateManager::setActiveAppState(APPSTATE_STAGE,
						new DataLoader(nickWrapper, tcpClient));
				break;
			case SERVER_FULL:
				connected = false;
				serverFull = true;
				break;
			default:
				break;
			}

		}
	}

	SDL_FreeSurface(userNick);
	userNick = NULL;
	userNick = TTF_RenderText_Blended(font, nickWrapper.c_str(), color);

	SDL_FreeSurface(userIp);
	userIp = NULL;
	userIp = TTF_RenderText_Blended(font, ipWrapper.c_str(), color);

}

void CAppStatePlayGame::onRender(SDL_Surface* surfDisplay) {
	int nickAddition = 0;
	int ipAddition = 0;

	if (surface) {
		CSurface::onDraw(surfDisplay, surface, 0, 0);
	}

	if (userNick != NULL) {
		CSurface::onDraw(surfDisplay, userNick, 370, 340);
		nickAddition = userNick->w;

	}
	if (userIp != NULL) {
		CSurface::onDraw(surfDisplay, userIp, 370, 420);
		ipAddition = userIp->w;
	}

	if (conf == NICK) {
		CSurface::onDraw(surfDisplay, bar, 370 + nickAddition, 340);
	}
	if (conf == IP) {
		CSurface::onDraw(surfDisplay, bar, 370 + ipAddition, 420);
	}

	if (error) {
		CSurface::onDraw(surfDisplay, errorSurface, 360, 290);
	}

	if (serverFull) {
		CSurface::onDraw(surfDisplay, serverFullSurface, 360, 290);
	}

}

CAppStatePlayGame * CAppStatePlayGame::getInstance() {
	return &instance;
}

CClientSocket * CAppStatePlayGame::getTcpClient() {
	return tcpClient;
}

